package com.cet.qz.unit01.chapter1_2;

import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdRandom;

import java.awt.*;

/**
 * @program: algorithm
 * @description:
 * @author: 陈恩涛
 * @create: 2021-03-04 09:25
 **/
public class Qz1_2_10 {



    public static void main(String[] args) {
        VisualCounter visualCounter = new VisualCounter(20, 10);
        for (int i = 0; i < 20; i++) {
            if (StdRandom.uniform(10) % 2 == 0) {
                visualCounter.increase();
            } else {
                visualCounter.decrease();
            }
        }
        System.out.println(visualCounter.getCount());
    }
}

class VisualCounter {
    private final int N;  //操作的最大次数
    private final int max; //计数器的最大绝对值
    private int count = 0;
    private int optCount = 0;

    public VisualCounter(int n, int max) {
        N = n;
        this.max = max;
        StdDraw.setPenColor(Color.blue);
        StdDraw.setXscale(0-1, N+1);
        StdDraw.setYscale(-(max+1),+(max+1));
        StdDraw.line(0-1,0,N+1,0);
        StdDraw.line(0,-(max+1),0,+(max+1));
        StdDraw.setPenColor(Color.red);
        StdDraw.setPenRadius(0.03);
    }

    public void increase() {
        if (count < max){
            count++;
        } else {
            throw new RuntimeException("计数器溢出！");
        }
        if (optCount++ < N) {
            StdDraw.point(optCount, count);
        } else {
            throw new RuntimeException("操作次数超出指定范围！");
        }
    }

    public void decrease() {
        if (count > -max){
            count--;
        } else {
            throw new RuntimeException("计数器溢出！");
        }
        if (optCount++ < N) {
            StdDraw.point(optCount, count);
        } else {
            throw new RuntimeException("操作次数超出指定范围！");
        }
    }

    public int getCount() {
        return count;
    }
}
